import json
import os

DATA_PATH = os.path.join(os.path.dirname(__file__), '../data/students.json')

## 
class Student:

    # 构造函数
    def __init__(self, name, age, gender, class_name):
        self.name = name
        self.age = age
        self.gender = gender
        self.class_name = class_name
    
    # 转为 字典
    def to_dict(self):
        return {
            'name': self.name,
            'age': self.age,
            'gender': self.gender,
            'class_name': self.class_name
        }
    
    @classmethod
    def from_dict(cls, data):
        return cls(
            data['name'],
            data['age'],
            data['gender'],
            data['class_name']
        )


## 直接保存到文件中
def save_students(students):
    """保存学生列表到文件"""
    with open(DATA_PATH, 'w', encoding='utf-8') as f:
        json.dump([s.to_dict() for s in students], f, ensure_ascii=False)


## 从文件中加载
def load_students():
    """从文件加载学生列表"""
    try:
        with open(DATA_PATH, 'r', encoding='utf-8') as f:
            return [Student.from_dict(data) for data in json.load(f)]
    except (FileNotFoundError, json.JSONDecodeError):
        return []